package ru.agiledev.wikiparser.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.util.Properties;

/**
 * Created by a.kirillov
 * Date: 2/11/12 Time: 9:51 AM
 */
public class Config {
     Logger logger = LoggerFactory.getLogger(Config.class);
	private static Config config;


    private String databaseUrl;
    private String databaseUsername;
    private String databasePwd;

    public static synchronized Config getInstance() {
		if(config == null) {
			config = new Config();
		}
		return config;
	}

    public Config() {
		Properties properties = loadProperties();
        if(properties != null) {
	        databaseUrl = (String)properties.get("databaseUrl");
            databaseUsername = (String)properties.get("databaseUsername");
			databasePwd = (String)properties.get("databasePwd");
        } else {
	        logger.error("Error loading property from config files. Load default HARD CODED TEST VALUES.");
             databaseUrl = "jdbc:mysql://80.77.85.46/wiktionary";
            databaseUsername = "wikiApp";
			databasePwd = "wiki_7ru57n01";
        }
	}


    private Properties loadProperties() {
		Properties properties = new Properties();
		try{
			properties.load(new FileInputStream("/opt/apache-tomcat-6.0.33/conf/apps/wiki.properties"));
			logger.warn("Properties read done via /opt/apache-tomcat-6.0.33/conf/apps/wiki.properties");
			return properties;
		} catch (Exception e) {
			logger.error("Unable to load property file from absolute path with error: " + e.getMessage() + ". Trying relative path.");
		}
		try{
			properties.load(new FileInputStream("../conf/apps/wiki.properties"));
			logger.warn("Properties read done via ../conf/apps/wiki.properties.");
			return properties;
		} catch (Exception e) {
			logger.error("Unable to load property file with error: " + e.getMessage());
		}

		return null;
	}

    public Logger getLogger() {
        return logger;
    }

    public void setLogger(Logger logger) {
        this.logger = logger;
    }

    public static Config getConfig() {
        return config;
    }

    public static void setConfig(Config config) {
        Config.config = config;
    }

    public String getDatabaseUrl() {
        return databaseUrl;
    }

    public void setDatabaseUrl(String databaseUrl) {
        this.databaseUrl = databaseUrl;
    }

    public String getDatabaseUsername() {
        return databaseUsername;
    }

    public void setDatabaseUsername(String databaseUsername) {
        this.databaseUsername = databaseUsername;
    }

    public String getDatabasePwd() {
        return databasePwd;
    }

    public void setDatabasePwd(String databasePwd) {
        this.databasePwd = databasePwd;
    }
}
